#include <pthread.h>
#include <iostream>
#include <vector>
#include <string>
#include <stdio.h>
#include <unistd.h>
using namespace std;

int tickets = 1000;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;

class threadData
{
public:
    threadData(int number)
    {
        threadname = "thread-" + to_string(number);
    }

public:
    string threadname;
};

void *threadRun(void *args)
{
    threadData *td = static_cast<threadData *>(args);
    const char *name = td->threadname.c_str();
    while (true)
    {
        pthread_mutex_lock(&lock);
        if (tickets > 0)
        {
            printf("I am %s,  tickets : %d  \n", name, tickets);
            tickets--;
            pthread_mutex_unlock(&lock);
        }
        else
        {
            pthread_mutex_unlock(&lock);
            break;
        }

        // 抢到票后的信息输入
        sleep(1);
    }
    return nullptr;
}
int main()
{
    vector<pthread_t> tids;
    vector<threadData *> datas;
    for (int i = 1; i <= 5; i++)
    {
        pthread_t t;
        threadData *data = new threadData(i);
        pthread_create(&t, nullptr, threadRun, data);

        tids.push_back(t);
        datas.push_back(data);
    }

    for (auto &t : tids)
    {
        pthread_join(t, nullptr);
    }

    for (auto &d : datas)
    {
        delete d;
    }
    return 0;
}